<?php

namespace App\TraitHelper;

use App\Models\User;
use Illuminate\Http\Request;
use Cookie;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

/**
 * Created by PhpStorm.
 * User: XingHuo
 * Date: 2016/11/19
 * Time: 下午11:50
 */
trait RequestHelper
{
    public $GRANT_TOKEN = '_token';
    public $APP_REQUEST_SIGN = '_s';

    function formatJson($success, array $data = [], $msg = '', $code = 0)
    {
        if (PHP_SAPI != 'cli') {
            header('Content-Type: application/json');
        }
        return json_encode(
            [
                'success' => $success,
                'data' => $data,
                'code' => $code,
                'msg' => $msg,
                'timestamp' => time()
            ]
        );
    }

    function getLoginUserInfo(Request $request=null, $asArray = true)
    {
        if (env('APP_ENV') == 'local') {
            return ['id'=>1];
        }
        try {
            JWTAuth::setRequest($request);
            $user = JWTAuth::parseToken('bearer', 'Authorization', '_token')->authenticate();
        } catch (TokenExpiredException $e) {
            $content = $this->formatJson(false, [], 'login_timeout', $e->getStatusCode());
            die($content);
        } catch (JWTException $e) {
            $content = $this->formatJson(false, [], 'login_invalid', $e->getStatusCode());
            die($content);
        }

        return $user->toArray();
    }

    function makeImageUrl($image, $size = '')
    {
        if (!$image) {
            return '';
        }
        if (strpos($image, '/public') === 0) {
            $image = str_replace('/public', '', $image);
            if ($size) {
                $pathinfo = pathinfo($image);
                $extension = $pathinfo['extension'];
                $image = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '.' . $size . 'x0.' . $extension;
            }
        }
        return url($image);
    }

    function getSignature($params, $secret, $getSignStr = false)
    {
        $str = '';  //待签名字符串
        //先将参数以其参数名的字典序升序进行排序
        ksort($params);
        //遍历排序后的参数数组中的每一个key/value对
        foreach ($params as $k => $v) {
            //为key/value对生成一个key=value格式的字符串，并拼接到待签名字符串后面
            $str .= "$k=$v";
        }
        //将签名密钥拼接到签名字符串最后面
        $str .= $secret;
        if ($getSignStr) {
            return $str;
        }
        //通过md5算法为签名字符串生成一个md5签名，该签名就是我们要追加的sign参数值
        return md5($str);
    }
    public function makeConfirmUrl($url, $title){
        return "javascript:if(confirm('$title')) location.href='$url';";
    }
}